var list = [
     {id: 7, name: '部门2-1', pid: 6},
    {id: 1, name: '部门1', pid: 0},
    {id: 2, name: '部门1-1', pid: 1},
    {id: 3, name: '部门1-2', pid: 1},
    {id: 4, name: '部门1-1-1', pid: 2},
    {id: 5, name: '部门1-2-1', pid: 3},
    {id: 6, name: '部门2', pid: 0},
    {id: 8, name: '部门3', pid: 0},
  ]


var out = (list) => {
  const tree = [];
const back = [];
    list.forEach(item => {

        if(item.pid === 0){
           tree.push(item)
        } else {
         const parent = tree.find(t => t.id === item.pid);
        if(parent){
            if(parent?.children){
                parent.children.push(item)
            }else {
                parent.children = [item]
             }
          } else {
                 back.push(item)
             }
        }
   })

    if(back.length){
         function setToChildrenByPid (item, tree){
//            console.log(item)
            const { pid } = item
            for(let i = 0; i < tree.length; i++){
                if(tree[i].id === pid){
                    tree[i]?.children ? tree[i].children.push(item) : tree[i].children = [item]
                } else {
                    if(tree[i]?.children && tree[i].children.length){
                        setToChildrenByPid(item, tree[i].children)
                     }
                }
            }
         }

           back.forEach(backItem => {
                    setToChildrenByPid(backItem, tree)
            })

    }

  console.log(tree, null, 4)


}

out(list);